package com.dwjm.exam.stu_list;

import com.dwjm.exam.pojo.Student;
import com.dwjm.exam.pojo.PageResult;
import com.dwjm.exam.stu_list.StudentDao;
import com.dwjm.utils.ConnectionDatabaseForMySQLUseJdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class StudentDaoImpl implements StudentDao {
    @Override
    public PageResult<Student> getStudentsByPage(int currentPage, int pageSize) {
        List<Student> students = new ArrayList<>();
        String countSql = "SELECT COUNT(*) FROM student";
        String querySql = "SELECT * FROM student LIMIT ?, ?";

        long totalRecords = 0;

        try (Connection conn = ConnectionDatabaseForMySQLUseJdbc.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet countRs = stmt.executeQuery(countSql)) {

            if (countRs.next()) {
                totalRecords = countRs.getLong(1);
            }

            try (PreparedStatement pstmt = conn.prepareStatement(querySql)) {
                int start = (currentPage - 1) * pageSize;
                pstmt.setInt(1, start);
                pstmt.setInt(2, pageSize);

                ResultSet rs = pstmt.executeQuery();
                while (rs.next()) {
                    Student student = mapRowToStudent(rs);
                    students.add(student);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取学生分页列表失败", e);
        }

        return new PageResult<>(currentPage, pageSize, totalRecords, students);
    }

    @Override
    public PageResult<Student> searchStudents(int currentPage, int pageSize, String name, String dormId) {
        List<Student> students = new ArrayList<>();
        StringBuilder countSql = new StringBuilder("SELECT COUNT(*) FROM student WHERE 1=1");
        StringBuilder querySql = new StringBuilder("SELECT * FROM student WHERE 1=1");

        List<Object> params = new ArrayList<>();

        if (name != null && !name.isEmpty()) {
            querySql.append(" AND name LIKE ?");
            countSql.append(" AND name LIKE ?");
            params.add("%" + name + "%");
        }

        if (dormId != null && !dormId.isEmpty()) {
            querySql.append(" AND dormId = ?");
            countSql.append(" AND dormId = ?");
            params.add(dormId);
        }

        querySql.append(" LIMIT ?, ?");

        long totalRecords = 0;
        try (Connection conn = ConnectionDatabaseForMySQLUseJdbc.getConnection();
             PreparedStatement countPstmt = conn.prepareStatement(countSql.toString())) {

            // 设置COUNT查询参数
            for (int i = 0; i < params.size(); i++) {
                countPstmt.setObject(i + 1, params.get(i));
            }

            ResultSet countRs = countPstmt.executeQuery();
            if (countRs.next()) {
                totalRecords = countRs.getLong(1);
            }

            // 执行分页查询
            try (PreparedStatement queryPstmt = conn.prepareStatement(querySql.toString())) {
                int paramIndex = 1;
                // 设置查询条件参数
                for (Object param : params) {
                    queryPstmt.setObject(paramIndex++, param);
                }

                // 设置分页参数
                int start = (currentPage - 1) * pageSize;
                queryPstmt.setInt(paramIndex++, start);
                queryPstmt.setInt(paramIndex, pageSize);

                ResultSet rs = queryPstmt.executeQuery();
                while (rs.next()) {
                    Student student = mapRowToStudent(rs);
                    students.add(student);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("搜索学生分页列表失败", e);
        }

        return new PageResult<>(currentPage, pageSize, totalRecords, students);
    }

    /**
     * 将ResultSet行映射到Student对象
     * @param rs 查询结果集
     * @return Student对象
     * @throws Exception
     */
    private Student mapRowToStudent(ResultSet rs) throws Exception {
        Student student = new Student();
        student.setStudentId(rs.getString("studentId"));
        student.setName(rs.getString("name"));
        student.setGender(rs.getString("gender"));
        student.setBirthDate(rs.getDate("birthDate"));
        student.setIdCard(rs.getString("idCard"));
        student.setCollege(rs.getString("college"));
        student.setMajor(rs.getString("major"));
        student.setClassName(rs.getString("className"));
        student.setStatus(rs.getString("status"));
        student.setDormId(rs.getString("dormId"));
        student.setBedNumber(rs.getString("bedNumber"));
        student.setPhone(rs.getString("phone"));
        student.setEmail(rs.getString("email"));
        student.setEmergencyContact(rs.getString("emergencyContact"));
        student.setUsername(rs.getString("username"));
        // 注意：密码通常不在这里返回
        return student;
    }
}